package com.ewhale.feitengguest.ui.auth

import android.graphics.Color
import android.os.Bundle
import android.os.CountDownTimer
import android.os.Handler
import android.text.Editable
import android.text.TextWatcher
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.view.View
import androidx.core.content.ContextCompat
import com.ewhale.feitengguest.R
import com.ewhale.feitengguest.dto.ArticleDetailDto
import com.ewhale.feitengguest.dto.LoginInfoDto
import com.ewhale.feitengguest.dto.TabEntity
import com.ewhale.feitengguest.presenter.user.auth.LoginPresenter
import com.ewhale.feitengguest.ui.WebViewActivity
import com.ewhale.feitengguest.ui.user.MainActivity
import com.ewhale.feitengguest.ui.shop.ShopMainActivity
import com.ewhale.feitengguest.ui.user.message.chat.AuthHelper
import com.ewhale.feitengguest.utils.Contants
import com.ewhale.feitengguest.utils.PickerUtils
import com.ewhale.feitengguest.utils.UserInfoUtils
import com.ewhale.feitengguest.view.auth.RegisterView
import com.flyco.tablayout.listener.CustomTabEntity
import com.flyco.tablayout.listener.OnTabSelectListener
import com.hyphenate.helpdesk.easeui.util.UserUtil
import com.orhanobut.hawk.Hawk
import com.simga.library.activity.MBaseActivity
import com.simga.library.utils.*
import kotlinx.android.synthetic.main.activity_register.*
import java.util.ArrayList

/**
 * 作者：SimGa
 * 日期：2019/12/25
 * 时间：10:37
 * 包名：com.ewhale.feitengguest.ui.auth
 */
class RegisterActivity : MBaseActivity<LoginPresenter>(), RegisterView, TextWatcher {
    private val mTabEntities = ArrayList<CustomTabEntity>()
    private var isPwdShow = false
    private var isPwd2Show = false
    override fun isUseBaseTitleBar(): Boolean {
        return true
    }

    override fun getViewId(): Int {
        return R.layout.activity_register
    }

    override fun init(savedInstanceState: Bundle?) {
        setTitle("注册")
        if (!Hawk.get(HawkKey.IS_USER_LOGIN, false) && !Hawk.get(HawkKey.IS_SHOP_LOGIN, false)) {
            mTabEntities.add(TabEntity("我是用户", 0, 0))
            mTabEntities.add(TabEntity("我是商家", 0, 0))
        } else {
            if (!Hawk.get(HawkKey.IS_SHOP_LOGIN, false)) {
                mTabEntities.add(TabEntity("我是商家", 0, 0))
                et_invite.visibility = View.INVISIBLE
                tv_regist.visibility = View.VISIBLE
                iv_icon_invite.setImageResource(R.mipmap.a_icon_choose)
            } else if (!Hawk.get(HawkKey.IS_USER_LOGIN, false)) {
                mTabEntities.add(TabEntity("我是用户", 0, 0))
            }
        }
        topMainTab.setTabData(mTabEntities)
    }

    override fun initListener() {
        super.initListener()
        et_regist_phone.addTextChangedListener(this)
        et_code.addTextChangedListener(this)
        et_registe_password.addTextChangedListener(this)
        et_registe_password_again.addTextChangedListener(this)
        et_invite.addTextChangedListener(this)
        topMainTab.setOnTabSelectListener(object : OnTabSelectListener {
            override fun onTabSelect(position: Int) {
                if (position == 0) {
                    et_invite.visibility = View.VISIBLE
                    tv_regist.visibility = View.INVISIBLE
                } else {
                    et_invite.visibility = View.INVISIBLE
                    tv_regist.visibility = View.VISIBLE
                }
                iv_icon_invite.setImageResource(if (position == 0) R.mipmap.a_icon_invite else R.mipmap.a_icon_choose)
            }

            override fun onTabReselect(position: Int) {
            }
        })
        iv_eye1.setOnClickListener {
            if (isPwdShow) {
                et_registe_password.transformationMethod = PasswordTransformationMethod.getInstance()
                iv_eye1.setImageResource(R.mipmap.a_icon_eyes_n)
            } else {
                et_registe_password.transformationMethod = HideReturnsTransformationMethod.getInstance()
                iv_eye1.setImageResource(R.mipmap.a_icon_eyes_s)
            }
            isPwdShow = !isPwdShow
        }
        iv_eye2.setOnClickListener {
            if (isPwd2Show) {
                et_registe_password_again.transformationMethod = PasswordTransformationMethod.getInstance()
                iv_eye2.setImageResource(R.mipmap.a_icon_eyes_n)
            } else {
                et_registe_password_again.transformationMethod = HideReturnsTransformationMethod.getInstance()
                iv_eye2.setImageResource(R.mipmap.a_icon_eyes_s)
            }
            isPwd2Show = !isPwd2Show
        }
        btn_getcode.setOnClickListener {
            val registerPhone = et_regist_phone.text.toString()
            if (CheckUtil.isNull(registerPhone)) {
                showToast("请输入手机号码")
                return@setOnClickListener
            }
            if (!StringUtil.isMobile(registerPhone)) {
                showToast("请输入正确手机号码")
                return@setOnClickListener
            }
            presenter.getCode(if (mTabEntities[topMainTab.currentTab].tabTitle == "我是用户") Hawk.get(HawkKey.USER_AUTHENTICATION, "") else Hawk.get(HawkKey.SHOP_AUTHENTICATION, ""), registerPhone)
        }
        btn_register.setOnClickListener {
            val registerPhone = et_regist_phone.text.toString()
            val code = et_code.text.toString()
            val registerPwd = et_registe_password.text.toString()
            val registerPwd2 = et_registe_password_again.text.toString()
            val inviteCode = et_invite.text.toString()
            if (CheckUtil.isNull(registerPhone)) {
                showToast("请输入手机号码")
                return@setOnClickListener
            }
            if (!StringUtil.isMobile(registerPhone)) {
                showToast("请输入正确手机号码")
                return@setOnClickListener
            }
            if (CheckUtil.isNull(code)) {
                showToast("请输入验证码")
                return@setOnClickListener
            }
            if (!CheckUtil.checkEqual(registerPwd, registerPwd2)) {
                showToast("两次密码不同，请重新确认密码")
                return@setOnClickListener
            }
            if (mTabEntities[topMainTab.currentTab].tabTitle == "我是商家") {
                if (CheckUtil.isNull(tv_regist.text.toString())) {
                    showToast("请选择个人注册或者是企业注册")
                    return@setOnClickListener
                }
            }
            presenter.register(if (mTabEntities[topMainTab.currentTab].tabTitle == "我是用户") 0 else 1, registerPhone, code, registerPwd, if(mTabEntities[topMainTab.currentTab].tabTitle == "我是用户") inviteCode else tv_regist.text.toString())
        }
        cb_aggree.setOnCheckedChangeListener { _, _ ->
            if (!checkInput()) {
                btn_register.apply {
                    isEnabled = false
                    setNormalSolid(Color.parseColor("#EEEEEE"))
                    setNormalStroke(1, Color.parseColor("#D4D4D4"))
                    setTextColor(Color.parseColor("#BBBBC2"))
                }
            } else {
                btn_register.apply {
                    isEnabled = true
                    setNormalSolid(ContextCompat.getColor(mContext, R.color.main_color))
                    setNormalStroke(1, ContextCompat.getColor(mContext, R.color.main_color))
                    setTextColor(Color.parseColor("#ffffff"))
                }
            }
        }
        tv_xieyi.setOnClickListener { presenter.loadArticleDetails(1) }
        tv_privacy.setOnClickListener { presenter.loadArticleDetails(11) }
        tv_regist.setOnClickListener {
            PickerUtils.getInstance().pickerOption(mContext, "请选择商家类型", arrayOf("个人", "企业"),object :PickerUtils.onCallBackOptions{
                override fun onOptionPicked(index: Int, item: String?) {
                    tv_regist.text = item
                }
            })
        }
    }

    override fun registerOrLoginSuccess(result: LoginInfoDto?) {
        saveLoginInfo(result!!)
//        if (mTabEntities[topMainTab.currentTab].tabTitle == "我是商家") {
//            saveLoginInfo(result!!)
//        } else {
//            Handler().postDelayed({
//                showLoading()
//                AuthHelper.getInstance().login(mContext, result!!.hxId, result.hxPassword, object : AuthHelper.AuthCallback {
//                    override fun onSuccess() {
//                        dismissLoading()
//                        saveLoginInfo(result)
//                    }
//
//                    override fun onError(errorCode: Int, errorStr: String) {
//                        dismissLoading()
//                        showToast("errorCode : $errorCode ! errorStr : $errorStr")
//                    }
//                })
//            }, 500)
//        }
    }

    fun saveLoginInfo(result: LoginInfoDto) {
        showToast("注册成功，正在登陆..")
        UserInfoUtils.saveLoginUserInfo(mTabEntities[topMainTab.currentTab].tabTitle , result)
        AppManager.get().finishAllActivity()
        if (result.type == 1) {//普通用户
            MainActivity.open(mContext)
        } else {//商家
            ShopMainActivity.open(mContext)
        }
    }

    override fun showProLoading() {
        showLoading()
    }

    override fun dimissProLoading() {
        dismissLoading()
    }

    override fun showErrorMessage(postCode: Int, code: String?, message: String?) {
        showErrorMsg(code, message)
    }

    override fun showDetail(result: ArticleDetailDto, type: Int) {
        WebViewActivity.open(mContext, if (type == 1) "用户协议" else "隐私协议", result.content)
    }

    override fun getCodeSuccess() {
        showToast("验证码已发送，请注意查收")
        mTimer.start()
    }

    private val mTimer = object : CountDownTimer(60 * 1000, 1000) {
        override fun onTick(millisUntilFinished: Long) {
            btn_getcode.apply {
                text = (millisUntilFinished / 1000).toString() + "s"
                setTextColor(ContextCompat.getColor(mContext, R.color.text_666666))
                isEnabled = false
                setNormalSolid(ContextCompat.getColor(mContext, R.color.default_window_color))
                setNormalStroke(1, ContextCompat.getColor(mContext, R.color.default_window_color))
            }
        }

        override fun onFinish() {
            btn_getcode.apply {
                text = "重新获取"
                setTextColor(ContextCompat.getColor(mContext, R.color.main_color))
                isEnabled = true
                setNormalSolid(ContextCompat.getColor(mContext, R.color.white))
                setNormalStroke(1, ContextCompat.getColor(mContext, R.color.main_color))
            }
        }
    }

    override fun afterTextChanged(s: Editable?) {}
    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        if (!checkInput()) {
            btn_register.apply {
                setNormalSolid(Color.parseColor("#EEEEEE"))
                setNormalStroke(1, Color.parseColor("#D4D4D4"))
                setTextColor(Color.parseColor("#BBBBC2"))
                isEnabled = false
            }
        } else {
            btn_register.apply {
                isEnabled = true
                setNormalSolid(ContextCompat.getColor(mContext, R.color.main_color))
                setNormalStroke(1, ContextCompat.getColor(mContext, R.color.main_color))
                setTextColor(Color.parseColor("#ffffff"))
            }
        }
    }

    /**
     * 检查输入框
     *
     * @return
     */
    private fun checkInput(): Boolean {
        if (CheckUtil.isNull(et_regist_phone.text.toString()) ||
                CheckUtil.isNull(et_code.text.toString()) ||
                CheckUtil.isNull(et_registe_password.text.toString()) ||
                CheckUtil.isNull(et_registe_password_again.text.toString()) ||
                !cb_aggree.isChecked) {
            return false
        }
        if (mTabEntities[topMainTab.currentTab].tabTitle == "我是商家") {
            if (CheckUtil.isNull(tv_regist.text.toString())) {
                return false
            }
            return true
        }
        return true
    }

    companion object {
        @JvmStatic
        fun open(mContext: MBaseActivity<*>) {
            mContext.startActivity(null, RegisterActivity::class.java)
        }
    }
}
